'use strict';
const db = uniCloud.database();
const users = db.collection('users');

// 测试用户信息
const TEST_USER = {
  openId: 'test_user',
  userNick: '测试用户',
  avatar: 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0',
  score: 0,
  winningCount: 0,
  gamesCount: 0,
  winningRate: 0
};

exports.main = async (event, context) => {
  const { action, data } = event;
  
  switch (action) {
    case 'login':
      return await login(data);
    case 'update':
      return await updateUser(data);
    case 'getInfo':
      return await getUserInfo(data);
    case 'updateStats':
      return await updateUserStats(data);
    default:
      return {
        code: -1,
        msg: '未知操作'
      };
  }
};

// 确保测试用户存在
async function ensureTestUser() {
  try {
    const testUser = await users.where({
      openId: TEST_USER.openId
    }).get();
    
    if (testUser.data.length === 0) {
      // 创建测试用户
      await users.add({
        ...TEST_USER,
        createTime: Date.now(),
        updateTime: Date.now()
      });
      console.log('测试用户创建成功');
    }
  } catch (e) {
    console.error('确保测试用户失败:', e);
  }
}

// 用户登录或注册
async function login(data) {
  // 确保测试用户存在
  await ensureTestUser();
  
  const { openId, userInfo } = data;
  
  try {
    // 查找用户是否存在
    const userResult = await users.where({
      openId: openId
    }).get();
    
    if (userResult.data.length > 0) {
      // 更新用户信息
      const updateData = {
        userNick: userInfo.nickName,
        avatar: userInfo.avatarUrl,
        updateTime: Date.now()
      };
      
      // 如果之前使用昵称作为openId，且现在获取到了真实openId，则更新openId
      if (userResult.data[0].openId === userInfo.nickName && 
          openId !== userInfo.nickName) {
        updateData.openId = openId;
      }
      
      await users.doc(userResult.data[0]._id).update(updateData);
      
      return {
        code: 0,
        msg: '登录成功',
        data: {
          ...userResult.data[0],
          ...updateData
        }
      };
    } else {
      // 创建新用户
      const userData = {
        openId,
        userNick: userInfo.nickName,
        avatar: userInfo.avatarUrl,
        score: 0,
        winningCount: 0,
        gamesCount: 0,
        winningRate: 0,
        createTime: Date.now(),
        updateTime: Date.now()
      };
      
      const result = await users.add(userData);
      
      return {
        code: 0,
        msg: '注册成功',
        data: {
          ...userData,
          _id: result.id
        }
      };
    }
  } catch (e) {
    console.error('登录失败:', e);
    return {
      code: -1,
      msg: '登录失败'
    };
  }
}

// 更新用户统计信息
async function updateUserStats(data) {
  const { openId, isWin = false } = data;
  
  try {
    const userResult = await users.where({
      openId: openId
    }).get();
    
    if (userResult.data.length === 0) {
      return {
        code: -1,
        msg: '用户不存在'
      };
    }
    
    const user = userResult.data[0];
    const updateData = {
      gamesCount: user.gamesCount + 1,
      winningCount: isWin ? user.winningCount + 1 : user.winningCount,
      updateTime: Date.now()
    };
    
    // 计算新的胜率
    updateData.winningRate = (updateData.winningCount / updateData.gamesCount) * 100;
    
    await users.doc(user._id).update(updateData);
    
    return {
      code: 0,
      msg: '更新成功',
      data: {
        ...user,
        ...updateData
      }
    };
  } catch (e) {
    console.error('更新统计信息失败:', e);
    return {
      code: -1,
      msg: '更新失败'
    };
  }
}

// 获取用户信息
async function getUserInfo(data) {
  const { openId } = data;
  
  try {
    const result = await users.where({
      openId: openId
    }).get();
    
    if (result.data.length === 0) {
      return {
        code: -1,
        msg: '用户不存在'
      };
    }
    
    return {
      code: 0,
      data: result.data[0]
    };
  } catch (e) {
    console.error('获取用户信息失败:', e);
    return {
      code: -1,
      msg: '获取用户信息失败'
    };
  }
}

// 更新用户信息
async function updateUser(data) {
  const { openId, updateData } = data;
  
  try {
    const userResult = await users.where({
      openId: openId
    }).get();
    
    if (userResult.data.length === 0) {
      return {
        code: -1,
        msg: '用户不存在'
      };
    }
    
    // 添加更新时间
    updateData.updateTime = Date.now();
    
    await users.doc(userResult.data[0]._id).update(updateData);
    
    return {
      code: 0,
      msg: '更新成功',
      data: {
        ...userResult.data[0],
        ...updateData
      }
    };
  } catch (e) {
    console.error('更新用户信息失败:', e);
    return {
      code: -1,
      msg: '更新失败'
    };
  }
} 